package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * ClassName: RedisIdWorker
 * Package: com.hmdp.utils
 * Description:
 *
 * @Author:
 * @Create: 2024/5/5 - 14:47
 * @Version: v1.0
 */
@Component
public class RedisIdWorker {

    // 随机定义一个开始的时间戳
    private static final long BEGIN_TIMESTAMP = 1040016000L;

    /**
     * 序列号的位数
     */
    private static final int COUNT_BITS = 32;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public long nextId(String keyPrefix) {
        // 1. 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long currentTimeSecond = now.toEpochSecond(ZoneOffset.UTC);
        // 用当前时间的时间戳减去 随机定义的时间戳
        long timestamp = currentTimeSecond - BEGIN_TIMESTAMP;

        // 2. 生成序列号
        // 2.1 获取当前日期，精确到天
        String currentDate = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 2.2 自增长
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + currentDate);
        // 3. 拼接并返回
        return timestamp << COUNT_BITS | count;
    }

/*    public static void main(String[] args) {
        // 获取任意时间的时间戳
        long second = LocalDateTime.of(2002, 12, 16, 5, 20).toEpochSecond(ZoneOffset.UTC);
        System.out.println(second);
    }*/
}
